package com.yearner.reviewplan.manage.system.bean;

import com.yearner.reviewplan.manage.system.entity.UserPerm;
import com.yearner.reviewplan.manage.system.entity.UserRouter;
import org.springframework.util.StringUtils;

/**
 * 创建 UserRouter 的工具类，并做一定的校验来判断是否锁定
 */
public class RouterFactory {

    public static UserRouter byPerm(UserPerm perm) {
        UserRouter router = new UserRouter();
        router.setUrl(perm.getUrl());
        String permission = perm.getPermName();
        // 默认RouterName 以 r_ 开头
        router.setRouterName(permission.startsWith("p_") ? "r_" + permission.substring(0, 2) : permission);
        router.setTitle(perm.getTitle());
        router.setPermission(permission);
        // 默认
        router.setCreator("admin");
        router.setRemark(perm.getRemark());
        router.setILock(lockSuggest(router));
        return router;
    }

    public static boolean lockSuggest(UserRouter router) {
        if (lockByUrl(router)) {
            return true;
        }
        if (lockByComponents(router)) {
            return true;
        }
        return false;
    }

    /**
     * 如果url为空，建议锁定
     *
     * @param router UserRouter
     * @return
     */
    private static boolean lockByUrl(UserRouter router) {
        return StringUtils.isEmpty(router.getUrl());
    }

    /**
     * 如果 Component 和 ComponentPath 都为空，也建议锁定
     * 通常只使用 Component
     * @param router UserRouter
     * @return
     */
    private static boolean lockByComponents(UserRouter router) {
        boolean firstFlag = StringUtils.isEmpty(router.getComponent())
                && StringUtils.isEmpty(router.getComponentPath());
        if (firstFlag) {
            return true;
        }
        // 若不为null，则消除可能存在的空格
        return StringUtils.isEmpty(router.getComponent().trim())
                && StringUtils.isEmpty(router.getComponentPath().trim());
    }
}
